// 音频处理类
class AudioProcessor {
  constructor() {
    this.localAudioContext = null;
    this.remoteAudioContext = null;
    this.localAnalyser = null;
    this.remoteAnalyser = null;
    this.localProcessor = null;
    this.remoteProcessor = null;
    this.isLocalRecording = true;  // 本地音频录制状态
    this.isRemoteRecording = true; // 远端音频录制状态
    this.onAudioData = null; // 音频数据回调
  }

  // 初始化本地音频捕获
  async initLocalAudioCapture(stream) {
    try {
      // 验证输入参数
      if (!stream || !stream.getAudioTracks || stream.getAudioTracks().length === 0) {
        throw new Error('无效的音频流或音频流中没有音频轨道');
      }

      this.localAudioContext = new (window.AudioContext || window.webkitAudioContext)();
      const source = this.localAudioContext.createMediaStreamSource(stream);

      this.localAnalyser = this.localAudioContext.createAnalyser();
      this.localAnalyser.fftSize = 2048;

      // 创建音频处理器
      this.localProcessor = this.localAudioContext.createScriptProcessor(4096, 1, 1);

      source.connect(this.localAnalyser);
      this.localAnalyser.connect(this.localProcessor);
      this.localProcessor.connect(this.localAudioContext.destination);

      this.localProcessor.onaudioprocess = (event) => {
        try {
          if (this.isLocalRecording && this.onAudioData) {
            const inputData = event.inputBuffer.getChannelData(0);
            const audioData = new Float32Array(inputData);

            // 添加本地音频数据调试
            if (Math.random() < 0.01) { // 1%概率输出调试信息
              const rms = Math.sqrt(audioData.reduce((sum, sample) => sum + sample * sample, 0) / audioData.length);
              console.log(`🎤 本地音频数据: ${audioData.length}样本, RMS=${rms.toFixed(4)}, 采样率=${this.localAudioContext.sampleRate}Hz`);
            }

            this.onAudioData({
              type: 'local',
              data: audioData,
              sampleRate: this.localAudioContext.sampleRate
            });
          }
        } catch (error) {
          console.error('处理本地音频数据失败:', error);
        }
      };

      console.log('本地音频捕获初始化成功');
    } catch (error) {
      console.error('初始化本地音频捕获失败:', error);
      throw error; // 重新抛出错误让调用者处理
    }
  }

  // 初始化远端音频捕获
  async initRemoteAudioCapture(stream) {
    try {
      // 验证输入参数
      if (!stream || !stream.getAudioTracks || stream.getAudioTracks().length === 0) {
        throw new Error('无效的远端音频流或音频流中没有音频轨道');
      }

      this.remoteAudioContext = new (window.AudioContext || window.webkitAudioContext)();
      const source = this.remoteAudioContext.createMediaStreamSource(stream);

      this.remoteAnalyser = this.remoteAudioContext.createAnalyser();
      this.remoteAnalyser.fftSize = 2048;

      // 创建音频处理器
      this.remoteProcessor = this.remoteAudioContext.createScriptProcessor(4096, 1, 1);

      source.connect(this.remoteAnalyser);
      this.remoteAnalyser.connect(this.remoteProcessor);
      this.remoteProcessor.connect(this.remoteAudioContext.destination);

      this.remoteProcessor.onaudioprocess = (event) => {
        try {
          if (this.isRemoteRecording && this.onAudioData) {
            const inputData = event.inputBuffer.getChannelData(0);
            const audioData = new Float32Array(inputData);

            // 添加远端音频数据调试
            if (Math.random() < 0.01) { // 1%概率输出调试信息
              const rms = Math.sqrt(audioData.reduce((sum, sample) => sum + sample * sample, 0) / audioData.length);
              console.log(`🔊 远端音频数据: ${audioData.length}样本, RMS=${rms.toFixed(4)}, 采样率=${this.remoteAudioContext.sampleRate}Hz`);
            }

            this.onAudioData({
              type: 'remote',
              data: audioData,
              sampleRate: this.remoteAudioContext.sampleRate
            });
          }
        } catch (error) {
          console.error('处理远端音频数据失败:', error);
        }
      };

      console.log('远端音频捕获初始化成功');
    } catch (error) {
      console.error('初始化远端音频捕获失败:', error);
      throw error; // 重新抛出错误让调用者处理
    }
  }

  // 开始录音
  startRecording() {
    this.isLocalRecording = true;
    this.isRemoteRecording = true;
    console.log('开始音频录制');
  }

  // 停止录音
  stopRecording() {
    this.isLocalRecording = false;
    this.isRemoteRecording = false;
    console.log('停止音频录制');
  }

  // 检查是否正在录音
  isCurrentlyRecording() {
    return this.isLocalRecording || this.isRemoteRecording;
  }

  // 控制本地音频录制
  setLocalRecording(enabled) {
    this.isLocalRecording = enabled;
    console.log('本地音频录制状态:', enabled ? '开启' : '关闭');
  }

  // 控制远端音频录制
  setRemoteRecording(enabled) {
    this.isRemoteRecording = enabled;
    console.log('远端音频录制状态:', enabled ? '开启' : '关闭');
  }

  // 获取录制状态
  getRecordingStatus() {
    return {
      local: this.isLocalRecording,
      remote: this.isRemoteRecording,
      overall: this.isLocalRecording || this.isRemoteRecording
    };
  }

  // 设置音频数据回调
  setAudioDataCallback(callback) {
    this.onAudioData = callback;
  }

  // 获取音频分析数据 (可用于可视化)
  getAudioAnalysisData(type = 'local') {
    const analyser = type === 'local' ? this.localAnalyser : this.remoteAnalyser;
    if (!analyser) return null;

    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);
    analyser.getByteFrequencyData(dataArray);

    return {
      frequencyData: dataArray,
      bufferLength: bufferLength
    };
  }

  // 检查是否有音频活动
  hasAudioActivity(type = 'local', threshold = 30) {
    const analysisData = this.getAudioAnalysisData(type);
    if (!analysisData) return false;

    const average = analysisData.frequencyData.reduce((a, b) => a + b) / analysisData.bufferLength;
    return average > threshold;
  }

  // 清理资源
  cleanup() {
    try {
      this.stopRecording();

      // 安全地断开和清理本地处理器
      if (this.localProcessor) {
        try {
          this.localProcessor.disconnect();
        } catch (error) {
          console.warn('断开本地音频处理器失败:', error);
        }
        this.localProcessor = null;
      }

      // 安全地断开和清理远端处理器
      if (this.remoteProcessor) {
        try {
          this.remoteProcessor.disconnect();
        } catch (error) {
          console.warn('断开远端音频处理器失败:', error);
        }
        this.remoteProcessor = null;
      }

      // 安全地关闭音频上下文
      if (this.localAudioContext) {
        try {
          this.localAudioContext.close();
        } catch (error) {
          console.warn('关闭本地音频上下文失败:', error);
        }
        this.localAudioContext = null;
      }

      if (this.remoteAudioContext) {
        try {
          this.remoteAudioContext.close();
        } catch (error) {
          console.warn('关闭远端音频上下文失败:', error);
        }
        this.remoteAudioContext = null;
      }

      this.localAnalyser = null;
      this.remoteAnalyser = null;
      this.onAudioData = null;

      console.log('音频处理器资源清理完成');
    } catch (error) {
      console.error('清理音频处理器资源时发生错误:', error);
    }
  }
}

// 导出类
window.AudioProcessor = AudioProcessor;
